package com.pijunn.report

import java.text.SimpleDateFormat;

import com.pijunn.common.MailingAddress;
import com.pijunn.label.Label;
import com.pijunn.report.Contact;
import com.pijunn.users.AppUser;

import grails.validation.Validateable;


@Validateable
class FoundEventCommand {
	def fmt = new SimpleDateFormat('MM/dd/yyyy HH:mm')
	
	Integer serialNumber
	Integer eventId
	//Integer contactid
	Integer itemId
	AppUser user
	String wizardStep
	String previous
	
	String description
	String found
	Date foundDate
	String location
	String venue
	
	Boolean useSms
	String phone
	Boolean contactdirect
	Contact contact = new Contact()
	MailingAddress mailing = new MailingAddress()
	
// Bug??? CamelCase form fields won't post to Command Object
//		Address getMailingAddress() {
//			if (!contact)
//				contact = new Contact(mailingAddress: new Address())
//			else if (!contact.mailingAddress)
//				contact.mailingAddress = new Address()
//				
//			return contact.mailingAddress
//		}
	
	static constraints = {
		serialNumber (blank: false, validator:{val, obj ->
			// Valid check
			def res = Label.findBySerialNumber(val)
			if (!res)
				return "found.invalid.serial"
		})
		wizardStep (blank: false)
		description (nullable: true, validator:{val, obj ->
			if (obj.wizardStep == 'confirm' && !obj.previous && !val)
				return 'found.description.blank.message'
		})
		found (nullable: true, validator:{val, obj ->
			if (obj.wizardStep == 'confirm' && !obj.previous) {
				if (!val)
					return 'found.time.blank.message'
				obj.foundDate = obj.fmt.parse(val)
				if (!obj.foundDate)
					return 'found.time.format'
			}
		})
		location (nullable: true, validator:{val, obj ->
			if (obj.wizardStep == 'confirm' && !obj.previous && !val)
				return 'found.location.blank.message'
		})
		venue (nullable: true, validator:{val, obj ->
			if (obj.wizardStep == 'confirm' && !obj.previous && !val)
				return 'found.venue.blank.message'
		})
		contact (nullable: true, validator:{val, obj ->
			if (obj.wizardStep == 'contact' && !obj.previous) {
				if (!val.name)
					return 'found.contactName.blank.message'
				if (!val.email)
					return 'found.email.blank.message'
				if (val.email && !val.email.matches(/^(?i)[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/))
					return 'found.contactEMail.matches.invalid'
			}
		})
		phone (nullable: true, validator:{val, obj ->
			if (obj.wizardStep == 'contact' && !obj.previous && !val)
				return 'found.contactPhone.blank.message'
			if (obj.wizardStep == 'contact' && !obj.previous && !val.matches(/^[+]?([0-9]*[\.\s\-\(\)]|[0-9]+){3,24}$/))
				return 'found.contactPhone.matches.invalid'
		})
	}
}
